<template>
  <div class="app-container">
    <!-- 体重 -->
    <el-row :gutter="0">
      <el-col :span="12">
        <span>体重趋势</span>
        <!-- <br> -->
        <!-- <span style="opacity: 0.6;">kg</span> -->
        <div id="weight" style="width: 500px; height: 400px;"></div>
      </el-col>
      <el-col :span="12">
        <span>体重记录</span>
        <el-table class="quarantine" stripe v-loading="loading" :data="tizhonglist"
          @selection-change="handleSelectionChange">
          <el-table-column label="测量时间" align="center" prop="time" width="180">
            <template #default="scope">
              <span>{{ parseTime(scope.row.time, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="数值&nbsp;&nbsp;(kg)" align="center" prop="number" />
          <el-table-column label="评估">
            <template #default="scope">
              <el-tag v-if="scope.row.number < 90" type="warning">偏瘦</el-tag>
              <el-tag v-if="scope.row.number >= 90 && scope.row.number < 150" type="success">正常</el-tag>
              <el-tag v-if="scope.row.number >= 150 && scope.row.number < 200" type="warning">偏胖</el-tag>
              <el-tag v-if="scope.row.number >= 200" type="danger">肥胖</el-tag>
            </template>

          </el-table-column>
          <el-table-column label="来源" align="center" prop="source">
            <template #default="scope">
              <dict-tag :options="healthlogsource" :value="scope.row.source" />
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link type="primary" @click="handleUpdate(scope.row)"
                v-hasPermi="['healthlog:healthlog:edit']">编辑</el-button>
              <el-button link type="danger" @click="handleDelete(scope.row)"
                v-hasPermi="['healthlog:healthlog:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table></el-col>
    </el-row>
    <!-- 血糖 -->
    <el-row :gutter="0">
      <el-col :span="12">
        <span>血糖趋势</span>
        <div id="xuetang" style="width: 500px; height: 400px;"></div>
      </el-col>
      <el-col :span="12">
        <span>血糖记录</span>
        <el-table class="quarantine" stripe v-loading="loading" :data="xuetanglist"
          @selection-change="handleSelectionChange">
          <el-table-column label="测量时间" align="center" prop="time" width="180">
            <template #default="scope">
              <span>{{ parseTime(scope.row.time, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="数值&nbsp;&nbsp; (mmol/L)" align="center" prop="number" />
          <el-table-column label="评估">
            <template #default="scope">
              <el-tag v-if="scope.row.number < 3.9" type="warning">低血糖</el-tag>
              <el-tag v-if="scope.row.number >= 3.9 && scope.row.number < 5.6" type="success">正常</el-tag>
              <el-tag v-if="scope.row.number >= 5.6" type="warning">糖尿病</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="来源" align="center" prop="source">
            <template #default="scope">
              <dict-tag :options="healthlogsource" :value="scope.row.source" />
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link type="primary" @click="handleUpdate(scope.row)"
                v-hasPermi="['healthlog:healthlog:edit']">编辑</el-button>
              <el-button link type="danger" @click="handleDelete(scope.row)"
                v-hasPermi="['healthlog:healthlog:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table></el-col>
    </el-row>

    <!-- 血压 -->
    <el-row :gutter="0">
      <el-col :span="12">
        <span>血压趋势</span>
        <div id="xueya" style="width: 500px; height: 400px;"></div>
      </el-col>
      <el-col :span="12">
        <span>血压记录</span>
        <el-table class="quarantine" stripe v-loading="loading" :data="xueyalist"
          @selection-change="handleSelectionChange">
          <el-table-column label="测量时间" align="center" prop="time" width="180">
            <template #default="scope">
              <span>{{ parseTime(scope.row.time, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="数值&nbsp;&nbsp; (mmHg)" align="center" prop="number" />
          <el-table-column label="评估">
            <template #default="scope">
              <el-tag v-if="scope.row.number < 120" type="warning">低血压</el-tag>
              <el-tag v-if="scope.row.number >= 120 && scope.row.number < 140" type="success">正常</el-tag>
              <el-tag v-if="scope.row.number >= 140" type="warning">高血压</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="来源" align="center" prop="source">
            <template #default="scope">
              <dict-tag :options="healthlogsource" :value="scope.row.source" />
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link type="primary" @click="handleUpdate(scope.row)"
                v-hasPermi="['healthlog:healthlog:edit']">编辑</el-button>
              <el-button link type="danger" @click="handleDelete(scope.row)"
                v-hasPermi="['healthlog:healthlog:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table></el-col>
    </el-row>
    <!-- 心率 -->
    <el-row :gutter="0">
      <el-col :span="12">
        <span>心率趋势</span>
        <div id="xinlv" style="width: 500px; height: 400px;"></div>
      </el-col>
      <el-col :span="12">
        <span>心率记录</span>
        <el-table class="quarantine" stripe v-loading="loading" :data="xinlvlist"
          @selection-change="handleSelectionChange">
          <el-table-column label="测量时间" align="center" prop="time" width="180">
            <template #default="scope">
              <span>{{ parseTime(scope.row.time, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="数值&nbsp;&nbsp;(bmp)" align="center" prop="number" />
          <el-table-column label="评估">
            <template #default="scope">
              <el-tag v-if="scope.row.number < 120" type="warning">偏低</el-tag>
              <el-tag v-if="scope.row.number >= 120 && scope.row.number < 140" type="success">正常</el-tag>
              <el-tag v-if="scope.row.number >= 140" type="warning">偏高</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="来源" align="center" prop="source">
            <template #default="scope">
              <dict-tag :options="healthlogsource" :value="scope.row.source" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link type="primary" @click="handleUpdate(scope.row)"
                v-hasPermi="['healthlog:healthlog:edit']">编辑</el-button>
              <el-button link type="danger" @click="handleDelete(scope.row)"
                v-hasPermi="['healthlog:healthlog:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table></el-col>
    </el-row>


    <!--     
    <el-table v-loading="loading" :data="tizhonglist" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="${comment}" align="center" prop="id" />
      <el-table-column label="数值" align="center" prop="number" />
      <el-table-column label="类型" align="center" prop="typeid">
        <template #default="scope">
          <dict-tag :options="sys_user_sex" :value="scope.row.typeid" />
        </template>
      </el-table-column>
      <el-table-column label="测量时间" align="center" prop="time" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.time, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="来源" align="center" prop="source">
        <template #default="scope">
          <dict-tag :options="healthlogsource" :value="scope.row.source" />
        </template>
      </el-table-column>
      <el-table-column label="居民" align="center" prop="userId">
        <template #default="scope">
          <dict-tag :options="sys_user_sex" :value="scope.row.userId" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['healthlog:healthlog:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['healthlog:healthlog:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table> -->
    <!-- <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" /> -->

    <!-- 添加或修改健康记录对话框 -->
    <el-dialog :title="title" v-model="open" width="400px" append-to-body>
      <el-form size="large" ref="healthlogRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item class="w300" label="类型" prop="typeid">
          <el-select v-model="form.typeid" placeholder="请选择类型">
            <el-option v-for="dict in typelist" :key="dict.id" :label="dict.type" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="w300" label="测量时间" prop="time">
          <el-date-picker clearable v-model="form.time" type="date" value-format="YYYY-MM-DD" placeholder="请选择测量时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item class="w300" label="数值" prop="number">
          <div style="display: flex; ">
            <el-input v-model="form.number" placeholder="请输入数值" />
            <span style="margin-left: 20px;">{{ danwei }}</span>
          </div>
        </el-form-item>


        <!-- <el-form-item label="来源" prop="source">
          <el-select v-model="form.source" placeholder="请选择来源">
            <el-option v-for="dict in healthlogsource" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item label="居民" prop="userId">
          <el-select v-model="form.userId" placeholder="请选择居民">
            <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 新增 -->
    <el-button type="primary" @click="handleAdd" v-hasPermi="['healthlog:healthlog:add']">添加健康记录</el-button>
    <el-button @click="todetail">返回</el-button>
  </div>
</template>

<script setup name="Healthlog">
// 定义组件接收的参数
const props = defineProps({
  userId: {
    type: Number,
    default: 1
  },
});
import { useRouter } from 'vue-router';
import useUserStore from '@/store/modules/user'
// 添加 nextTick 相关引用
import { nextTick } from 'vue'
import { getlogtype, listHealthlog, getHealthlog, delHealthlog, addHealthlog, updateHealthlog } from "@/api/healthlog/healthlog";
import { listType } from "@/api/type/type";
const user = useUserStore()
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    number: null,
    typeid: null,
    time: null,
    source: null,
    userId: null
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);
const { proxy } = getCurrentInstance();
const { healthlogsource, sys_user_sex } = proxy.useDict('healthlogsource', 'sys_user_sex');

const healthlogList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
let danwei = ref('');

watch(() => form.value.typeid, (newValue) => {
  // 这里可以添加当 form.typeid 变化时要执行的逻辑
  typelist.value.forEach(item => {
    if (item.id == newValue) {
      switch (item.type) {
        case '体重':
          danwei.value = 'kg';
          break;
        case '血糖':
          danwei.value = 'mmol/L';
          break;
        case '血压':
          danwei.value = 'mmHg';
          break;
        case '心率':
          danwei.value = 'bmp';
          break;
      }

    }
  })

});

//返回主页
const router = useRouter();
function todetail() {
  router.push({ path: 'resident' });
}
// 查询类型
let typelist = ref([])
function gettype() {
  loading.value = true;
  return new Promise((resolve, reject) => {
    listType().then(response => {
      typelist.value = response.rows;
      console.log('typelist.value', typelist.value);
      loading.value = false;
      resolve(1)
    });
  });
}
/** 查询健康记录列表 */
// function getList() {
//   loading.value = true;
//   queryParams.value.userId = props.userId;

//   listHealthlog(queryParams.value).then(response => {

//     healthlogList.value = response.rows;
//     total.value = response.total;
//     loading.value = false;
//   });
// }
// 修改 getList 方法

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    number: null,
    typeid: null,
    time: null,
    source: null,
    userId: null
  };
  proxy.resetForm("healthlogRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加健康记录";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getHealthlog(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改健康记录";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["healthlogRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        form.value.userId = props.userId;
form.value.source=1;
        updateHealthlog(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
form.value.userId = props.userId;
form.value.source=1;
        addHealthlog(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除健康记录编号为"' + _ids + '"的数据项？').then(function () {
    return delHealthlog(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('healthlog/healthlog/export', {
    ...queryParams.value
  }, `healthlog_${new Date().getTime()}.xlsx`)
}



const getMonthAndDay = (dateStr) => {
  const date = new Date(dateStr);
  const month = date.getMonth() + 1; // 月份从 0 开始，所以要加 1
  const day = date.getDate();
  return `${month}/${day}`;
};

//查询体重
let tizhonglist = ref([])
function gettizhong() {

  loading.value = true;

  return new Promise((resolve, reject) => {
    getlogtype({ userid: props.userId, typeid: 1 }).then(response => {
      tizhonglist.value = response.rows;
      console.log('tizhong', response.rows);
      loading.value = false;
      resolve(1)

    })
  })
}

//查询血糖
let xuetanglist = ref([])
function getxuetang() {
  loading.value = true;
  return new Promise((resolve, reject) => {
    getlogtype({ userid: props.userId, typeid: 2 }).then(response => {
      console.log('xuetang', response.rows);
      xuetanglist.value = response.rows;
      loading.value = false;
      resolve(1)
    })
  })
}

//查询血压
let xueyalist = ref([])
function getxueya() {
  loading.value = true;
  return new Promise((resolve, reject) => {
    getlogtype({ userid: props.userId, typeid: 3 }).then(response => {

      console.log('xueya', response.rows);
      xueyalist.value = response.rows;
      loading.value = false;
      resolve(1)
    })
  })
}

//查询心率
let xinlvlist = ref([])
function getxinlv() {
  loading.value = true;
  return new Promise((resolve, reject) => {
    getlogtype({ userid: props.userId, typeid: 4 }).then(response => {
      console.log('xinlv', response.rows);
      xinlvlist.value = response.rows;
      loading.value = false;
      resolve(1)
    })
  })
}


//echarts
import { onMounted, watch } from 'vue';
import * as echarts from 'echarts';
import { ref } from "vue";
// ... existing code ...

// 初始化ECharts图表
const etizhong = () => {
  const chartDom = document.getElementById('weight');
  const myChart = echarts.init(chartDom);
  let datalist = ref([])
  let valuelist = ref([])
  tizhonglist.value.forEach(item => {
    // console.log('item', item);
    const monthAndDay = getMonthAndDay(item.time); // 获取月份和日期
    datalist.value.push(monthAndDay); // 将日期和数值添加到数组中
    valuelist.value.push(item.number); // 将日期和数值添加到数组中
  });
  const option = {
    xAxis: {
      type: 'category',
      data: datalist.value
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: valuelist.value,
        type: 'line',
        smooth: true // 设置为平滑折线图
      }
    ]
  };
  option && myChart.setOption(option);
};
const exuetang = () => {
  const chartDom = document.getElementById('xuetang');
  const myChart = echarts.init(chartDom);
  let datalist = ref([])
  let valuelist = ref([])
  xuetanglist.value.forEach(item => {
    // console.log('item', item);
    const monthAndDay = getMonthAndDay(item.time); // 获取月份和日期
    datalist.value.push(monthAndDay); // 将日期和数值添加到数组中
    valuelist.value.push(item.number); // 将日期和数值添加到数组中
  });
  const option = {
    xAxis: {
      type: 'category',
      data: datalist.value
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: valuelist.value,
        type: 'line',
        smooth: true // 设置为平滑折线图
      }
    ]
  };
  option && myChart.setOption(option);
};
const exueya = () => {
  const chartDom = document.getElementById('xueya');
  const myChart = echarts.init(chartDom);
  let datalist = ref([])
  let valuelist = ref([])
  xueyalist.value.forEach(item => {
    // console.log('item', item);
    const monthAndDay = getMonthAndDay(item.time); // 获取月份和日期
    datalist.value.push(monthAndDay); // 将日期和数值添加到数组中
    valuelist.value.push(item.number); // 将日期和数值添加到数组中
  });
  const option = {
    xAxis: {
      type: 'category',
      data: datalist.value
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: valuelist.value,
        type: 'line',
        smooth: true // 设置为平滑折线图
      }
    ]
  };
  option && myChart.setOption(option);
};
const exinlv = () => {
  const chartDom = document.getElementById('xinlv');
  const myChart = echarts.init(chartDom);
  let datalist = ref([])
  let valuelist = ref([])
  xinlvlist.value.forEach(item => {
    // console.log('item', item);
    const monthAndDay = getMonthAndDay(item.time); // 获取月份和日期
    datalist.value.push(monthAndDay); // 将日期和数值添加到数组中
    valuelist.value.push(item.number); // 将日期和数值添加到数组中
  });
  const option = {
    xAxis: {
      type: 'category',
      data: datalist.value
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: valuelist.value,
        type: 'line',
        smooth: true // 设置为平滑折线图
      }
    ]
  };
  option && myChart.setOption(option);
};

// 在组件挂载后初始化图表
// onMounted(async () => {
//   await gettizhong();
//   await getxuetang();
//   await getxueya();
//   await getxinlv();
//   await gettype();
//   etizhong();
//   exuetang();
//   exueya();
//   exinlv();
// });
// onMounted(async () => {
//   await getList(); // 等待 getList 方法执行完成
// })
async function getList() {
  await gettizhong();
  await getxuetang();
  await getxueya();
  await getxinlv();
  await gettype();
  

  etizhong();
  exuetang();
  exueya();
  exinlv();

}
// 添加 resize 监听
// onMounted(() => {
//   window.addEventListener('resize', () => {
//     echarts.init(document.getElementById('weight')).resize();
//     echarts.init(document.getElementById('xuetang')).resize();
//     echarts.init(document.getElementById('xueya')).resize();
//     echarts.init(document.getElementById('xinlv')).resize();
//   });
// });
getList();
</script>
<style scoped>
.w300 {
  width: 300px
}
.quarantine{
  margin-top: 20px;
}
</style>